package com.sixmac.police.controller;

import com.sixmac.common.base.BaseController;
import com.sixmac.core.constant.Constant;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.plugins.dao.Db;
import com.sixmac.core.plugins.dao.Md;
import com.sixmac.core.toolbox.Paras;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.kit.DateKit;
import com.sixmac.core.toolbox.kit.JsonKit;
import com.sixmac.module.AdminUser;
import com.sixmac.module.Room;
import com.sixmac.module.TenantLive;
import com.sixmac.platform.service.RoomService;
import com.sixmac.user.ExcelUtil;
import com.sixmac.user.ExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * AdminRoleController
 * 2018-09-26 11:15:35
 * @author Blade
 */
@Controller
@RequestMapping("/admin/live")
public class AdminLiveController extends BaseController {
	private static String CODE = "room";
	private static String PREFIX = "t_tenant_live";
	private static String LIST_SOURCE = "live.list";
	private static String BASE_PATH = "/police/";

	@RequestMapping(KEY_MAIN)
	public String index(ModelMap mm) {
		AdminUser user = (AdminUser) getRequest().getSession().getAttribute(Constant.SESSION_ADMIN_USER);
		String areaIds = Db.queryStr("SELECT GROUP_CONCAT(u.areaId) areaId FROM t_admin_user u WHERE FIND_IN_SET( u.id, queryAllChildByOrg ('"+user.getId()+"') )",null);
		String areaIds2 = Db.queryStr("SELECT GROUP_CONCAT(area.areaCode) areaCode from t_region_area area LEFT JOIN t_admin_user u ON u.cityId = area.cityCode WHERE u.id is not null and u.id = "+user.getId(),null);
		String area = null;
		if (areaIds!=null&&areaIds2!=null){
			area = areaIds+","+areaIds2;
		}else if (areaIds!=null&&areaIds2==null){
			area = areaIds;
		}else if (areaIds==null&&areaIds2!=null){
			area =areaIds2;
		}
		String startDate = getParameter("startDate");
		String endDate = getParameter("endDate");
		String name = getParameter("name");
		String mobile = getParameter("mobile");
		String idCard = getParameter("idCard");
		Integer sex = getParameterToInt("sex");
		Paras paras = Paras.create().set("startDate",startDate).set("areaIds",area).set("endDate",endDate).set("name",name).set("mobile",mobile).set("idCard",idCard).set("sex",sex);
		Object grid = paginate(Md.getSql(LIST_SOURCE,paras));
		mm.put("grid",grid);
		return BASE_PATH + "residence_list.html";
	}

	@RequestMapping(KEY_ADD)
	public String add(ModelMap mm) {
		mm.put("code", CODE);
		return BASE_PATH + "room_add.html";
	}

	@RequestMapping(KEY_EDIT + "/{id}")
	public String edit(@PathVariable Integer id, ModelMap mm) {
		TenantLive room = Blade.create(TenantLive.class).findById(id);
		mm.put("model", JsonKit.toJson(room));
		mm.put("id", id);
		mm.put("code", CODE);
		return BASE_PATH + "room_edit.html";
	}

	@RequestMapping(KEY_VIEW + "/{id}")
	public String view(@PathVariable Integer id, ModelMap mm) {
		TenantLive room =  Blade.create(TenantLive.class).findById(id);
		mm.put("model", JsonKit.toJson(room));
		mm.put("id", id);
		mm.put("code", CODE);
		return BASE_PATH + "room_view.html";
	}

	@ResponseBody
	@RequestMapping(KEY_LIST)
	public Object list() {
		Object grid = paginate(LIST_SOURCE);
		return grid;
	}

	@ResponseBody
	@RequestMapping(KEY_SAVE)
	public AjaxResult save() {
		TenantLive room = mapping(PREFIX, TenantLive.class);
		boolean temp = Blade.create(TenantLive.class).save(room);
		if (temp) {
			return success(SAVE_SUCCESS_MSG);
		} else {
			return error(SAVE_FAIL_MSG);
		}
	}

	@ResponseBody
	@RequestMapping("/confirm")
	public AjaxResult confirm() {
		Integer id = getParameterToInt("id");
		TenantLive tenantLive = new TenantLive();
		tenantLive.setId(id);
		tenantLive.setStatus(2);
		boolean temp = Blade.create(TenantLive.class).update(tenantLive);
		if (temp) {
			return success(SAVE_SUCCESS_MSG);
		} else {
			return error(SAVE_FAIL_MSG);
		}
	}

	@ResponseBody
	@RequestMapping(KEY_UPDATE)
	public AjaxResult update() {
		TenantLive room = mapping(PREFIX, TenantLive.class);
		boolean temp = Blade.create(TenantLive.class).update(room);
		if (temp) {
			return success(UPDATE_SUCCESS_MSG);
		} else {
			return error(UPDATE_FAIL_MSG);
		}
	}

	@ResponseBody
	@RequestMapping(KEY_REMOVE)
	public AjaxResult remove(@RequestParam String ids) {
		int cnt = Blade.create(TenantLive.class).deleteByIds(ids);
		if (cnt > 0) {
			return success(DEL_SUCCESS_MSG);
		} else {
			return error(DEL_FAIL_MSG);
		}
	}

	@RequestMapping("/export")
	public void exportOrderList(String ids, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String excelName = "居住证申请列表" + DateKit.getDays()+ ".xls";

		try {
			AdminUser user = (AdminUser) getRequest().getSession().getAttribute(Constant.SESSION_ADMIN_USER);
			String areaIds = Db.queryStr("SELECT GROUP_CONCAT(u.areaId) areaId FROM t_admin_user u WHERE FIND_IN_SET( u.id, queryAllChildByOrg ('"+user.getId()+"') )",null);
			String areaIds2 = Db.queryStr("SELECT GROUP_CONCAT(area.areaCode) areaCode from t_region_area area LEFT JOIN t_admin_user u ON u.cityId = area.cityCode WHERE u.id is not null and u.id = "+user.getId(),null);
			String area = null;
			if (areaIds!=null&&areaIds2!=null){
				area = areaIds+","+areaIds2;
			}else if (areaIds!=null&&areaIds2==null){
				area = areaIds;
			}else if (areaIds==null&&areaIds2!=null){
				area =areaIds2;
			}

			String startDate = getParameter("startDate");
			String endDate = getParameter("endDate");
			String name = getParameter("name");
			String mobile = getParameter("mobile");
			String address = getParameter("address");
			Integer status = getParameterToInt("status");
			Paras paras = Paras.create().set("startDate",startDate).set("areaIds",area).set("endDate",endDate).set("name",name).set("mobile",mobile).set("address",address).set("status",status);
			String sql = Md.getSql(LIST_SOURCE,paras);
			if (ids.trim().length()>0){
				sql = "SELECT aa.* from("+sql+")aa where aa.id in("+ids+")";
			}
			List<Map> landlords = Db.selectList(sql);
			List<Map<String,Object>> list = new ArrayList<>();
			for (Map map:landlords) {
				Map<String,Object> hashMap = new HashMap<>();
				hashMap.putAll(map);
				String type = "未入住";
				if (map.get("approve")!=null){
					Integer approve = Integer.valueOf(map.get("approve").toString());
					if (approve == 3){
						type = "申请中";
					}
				}
				if (!type.equals("申请中")){
					if (map.get("status")==null){
						type = "未入驻";
					}else{
						Integer tenantStatus = Integer.valueOf(map.get("status").toString());
						if (tenantStatus == 1){
							type="已入住";
						}else if(tenantStatus == 2){
							type="已退租";
						}
					}
				}
				Integer sex1 = Integer.valueOf(map.get("sex").toString());
				String sex = "男";
				if (sex1 == 1){
					sex="男";
				}else if(sex1 == 2){
					sex="女";
				}
				Integer livestatus = Integer.valueOf(map.get("livestatus").toString());
				String livestatusName = "未受理";
				if (livestatus == 1){
					livestatusName="未受理";
				}else if(livestatus == 2){
					livestatusName="已经受理";
				}
				hashMap.put("sexName",sex);
				hashMap.put("statusName",type);
				hashMap.put("livestatusName",livestatusName);
				hashMap.put("createDateName",DateKit.format((Date)(map.get("createDate")), "yyyy-MM-dd HHmmss"));
				hashMap.put("birthdayName",map.containsKey("birthday")?DateKit.format((Date) (map.get("birthday")), "yyyy-MM-dd HHmmss"):"");
				list.add(hashMap);
			}
			ExcelUtil.createExcel(ExportUtil.LIVE_LIST_TEMPLATE, ExportUtil.LIVE_LIST_FIELD, list, ExportUtil.tempFilePath);
			download(request, response, excelName, ExportUtil.tempFilePath);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
